<template>
    <div>
      <video src="" id="video"></video>
      <div class="serve_content">
        <p v-for="(v,i) in serveContent" :key="i">
            {{ v }}
        </p>
      </div>
    </div>
  </template>
   
  <script>
  const H264 = require('h264-converter');
  export default {
    name: 'VideoStreamDecoder',
    data(){
        return{
            wsUrl:'',
            serveContent:[],
        }
    },
    mounted() {
        this.wsUrl = window.config.wsUrl;
        // this.wsUrl = 'ws://127.0.0.1:8002';
      this.connectWebSocket();
    },
    methods: {
      connectWebSocket() {
        const video = document.getElementById('video');
        this.webSocket = new WebSocket(this.wsUrl);
        this.webSocket.binaryType = 'arraybuffer';
   
        this.webSocket.onopen = () => {
          console.log('WebSocket connected');
        };
   
        this.webSocket.onmessage = (event) => {
            console.log(event)
            this.serveContent.push(event.data);
            H264.decode(event.data).then(function(arrayBuffer){
                const blob = new Blob([arrayBuffer],{type:'video/webm'});
                const url = URL.createObjectURL(blob);
                video.src = url;
            })
        //   if (event.data instanceof ArrayBuffer) {
        //     // 假设你已经有方法将ArrayBuffer转换为ImageData
        //     const imageData = this.decodeArrayBufferToImageData(event.data);
        //     if (imageData) {
        //       this.renderVideoFrame(imageData);
        //     }
        //   }
        };
   
        this.webSocket.onerror = (error) => {
          console.error('WebSocket error:', error);
        };
   
        this.webSocket.onclose = () => {
          console.log('WebSocket disconnected');
        };
      },
      decodeArrayBufferToImageData(arrayBuffer) {
        // 这里应该是你解码ArrayBuffer为ImageData的逻辑
        // 这个逻辑取决于你使用的解码库，例如libvips, wasm-mpp等
        // 返回ImageData或null
      },
      renderVideoFrame(imageData) {
        const canvas = this.$refs.canvas;
        const ctx = canvas.getContext('2d');
        canvas.width = imageData.width;
        canvas.height = imageData.height;
        ctx.putImageData(imageData, 0, 0);
      }
    },
    beforeDestroy() {
      if (this.webSocket) {
        this.webSocket.close();
      }
    }
  };
  </script>
<style>
#video{
    width: 100%;
    height: 300px;
    object-fit: contain;
    background-color: #000;
}
.serve_content{
    width: 100%;
    height: 200px;
    overflow-y: auto;
}
.serve_content p{
    line-height: 20px;
    font-size: 20px;
}
</style>